<?php
/**
 * APP 支付算签
 */
namespace App\Libraries;

use App\Models\Config;

include_once 'wechat_pay/lib/WxPay.Api.php';
include_once 'alipay_sdk/AopSdk.php';
class AppRefund {
	
	/**
	 * @param $param
	 * 微信退款
	 */
	public function wechat($param){

		$input = new \WxPayRefund();
		//$input->SetOut_trade_no($param['out_trade_no']);
		$input->SetOut_refund_no($param['out_refund_no']);
		$input->SetTotal_fee($param['total_fee'] * 100);		// 分为单位，数据表是元为单位，故乘100
        $input->SetTransaction_id($param['transaction_id']);
        $input->SetRefund_fee($param['refund_fee']*100);
        $input->SetRefund_desc($param['refund_desc']);
		$order = \WxPayApi::refund($input);

        return $order;
	}
	
	// 微信支付回调算签，成功返回true，失败返回false
	public function wechatCheckSign(){
		// return bool
		$error_msg = '';
		$status = \WxpayApi::notify(array($this, 'wechatCheckSignSuccess'), $error_msg);
		return $status;
	}
	// 原xml转数组后参数原样返回
	public function wechatCheckSignSuccess($post){
		return $post;
	}
	
	
	/**
	 * @param $param
	 * 支付宝退款
	 */
	public function alipay($param){
		$aop = new \AopClient();
		$appid = Config::key('alipay_appid')->value('value');
		//$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
		$aop->appId = $appid;
//		$aop->rsaPrivateKey = '请填写开发者私钥去头去尾去回车，一行字符串';
		$aop->rsaPrivateKey = file_get_contents(__DIR__.'/alipay_sdk/pem/rsa_private_key.pem');
//		$aop->alipayrsaPublicKey='请填写支付宝公钥，一行字符串';
		$aop->alipayrsaPublicKey = file_get_contents(__DIR__.'/alipay_sdk/pem/alipay_public_key.pem');
		$aop->apiVersion = '1.0';
		$aop->signType = 'RSA2';
		$aop->postCharset='UTF-8';
		$aop->format='json';
		$request = new \AlipayTradeRefundRequest();
		$bizcontent = json_encode([
			'trade_no'=>$param['transaction_id'],
            'refund_amount'=>$param['refund_fee'],
            'refund_reason'=>$param['refund_desc'],
            'out_request_no'=>$param['out_refund_no'],
		]);
		$request->setBizContent($bizcontent);
		$result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        $msg = $result->$responseNode->msg;
        $return = array();
        if(!empty($resultCode)&&$resultCode == 10000){
            $return['result_code']='SUCCESS';
        } else {
            $return['result_code']=$msg;
            $return['err_code_des'] = $result->$responseNode->sub_msg;
        }
		return $return;
	}
	
	// 支付宝支付算签
	public function alipayCheckSign(){
		$aop = new \AopClient();
		$aop->alipayrsaPublicKey = file_get_contents(__DIR__.'/alipay_sdk/pem/alipay_public_key.pem');
		$flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
		return $flag;
	}

	public function bank_union($order_no,$procut_name,$price,$notify_url){
	
	}
}